namespace Todos.Application.TodoLists.Commands;

[AuthConfig(typeof(TodoItem), ResourceAccessType.RoleLimit, "ChangeItemStatus")]
public class ChangeTodoItemStatusCommand : IRequest<ApiResult>, ICommand
{
    public long ListId { get; set; }
    public long ItemId { get; set; }
    public TodoStatus Status { get; set; }
}

public class ChangeTodoItemStatusCommandHandler(IRepository<TodoList> repository) : IRequestHandler<ChangeTodoItemStatusCommand, ApiResult>
{
    public async Task<ApiResult> Handle(ChangeTodoItemStatusCommand request, CancellationToken cancellationToken)
    {
        var spec = new TodoListByIdSpec(request.ListId).And(new TodoListIncludeItemsSpec());
        var list = await repository.GetAsync(spec, cancellationToken);
        if (list == null)
        {
            return new ApiResult(ApiResultType.Error, "待办列表不存在");
        }
        list.ChangeItemStatus(request.ItemId, request.Status);
        await repository.UpdateAsync(list, cancellationToken);
        return new ApiResult(ApiResultType.Success, $"待办项状态已变更为：{request.Status}");
    }
}

public class ChangeTodoItemStatusCommandValidator : AbstractValidator<ChangeTodoItemStatusCommand>
{
    public ChangeTodoItemStatusCommandValidator()
    {
        RuleFor(m => m.ListId).NotEmpty().WithMessage("待办列表Id不能为空");
        RuleFor(m => m.ItemId).NotEmpty().WithMessage("待办项Id不能为空");
        RuleFor(m => m.Status).IsInEnum().WithMessage("待办项状态无效");
    }
}
